<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <ContentWrap>
      <el-form :model="queryParams" ref="queryFormRef" :inline="true">
        <el-form-item label="选中联系人首个邮箱" prop="isSelectFirstMail">
          <el-checkbox
            v-model="filterParams.isSelectFirstMail"
            @change="handleIsSelectFirstMailChange"
          />
        </el-form-item>
        <el-form-item label="仅选中主联系人" prop="isOnlyMailContact">
          <el-checkbox
            v-model="filterParams.isOnlyMainContact"
            @change="handleIsOnlyMailContactChange"
          />
        </el-form-item>
        <el-form-item label="显示离职联系人" prop="isShowResignContact">
          <el-checkbox
            v-model="filterParams.isShowResignContact"
            @change="handleIsShowResignContactChange"
          />
        </el-form-item>
      </el-form>
      <Table
        ref="tableRef"
        :columns="columns"
        :adaptive="true"
        :data="queryData"
        :row-style="rowStyle"
        @select="handleTableSelectChange"
        @select-all="handleTableSelectChange"
      />
    </ContentWrap>
    <template #footer>
      <el-text>（已选中{{ selectCount }}个 ）</el-text>
      <el-button type="primary" @click="handleClickNextStep">下一步</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
  <MailMarketEdit ref="marketEditRef" @success="mailMarketSuccess" />
</template>
<script setup name="MailMarketSelect" lang="ts">
import * as CustomerApi from '@/api/customer/customer'
import * as BusinessFieldApi from '@/api/setting/businessField'
import MailMarketEdit from '@/views/market/mailMarket/MailMarketEdit.vue'
const message = useMessage() // 消息弹窗
const marketEditRef = ref()
const selectCount = ref(0)
const dialogTitle = ref('邮件营销')
const dialogVisible = ref(false)
const queryData = ref()
const queryFormRef = ref()
const queryParams = ref({})
const resignOptionId = ref()
const tableRef = ref()
const filterParams = ref({
  isIndeterminate: false,
  isSelectFirstMail: true,
  isOnlyMainContact: true,
  isShowResignContact: false
})
const columns = [
  {
    type: 'selection',
    align: 'center'
  },
  {
    label: '邮件地址',
    prop: 'mailAddress',
    formatter: (row) => row.contact.name + '<' + row.mailAddress + '>'
  },
  {
    label: '职位',
    prop: 'contact.position'
  },
  {
    label: '客户',
    prop: 'contact.customer.name'
  }
]
/** 打开弹窗 */
const open = async (ids) => {
  dialogVisible.value = true
  resetForm()
  resignOptionId.value = await BusinessFieldApi.getWorkStateResignOptionId()
  queryData.value = await CustomerApi.getMailInfoByCustomerIds({ ids: ids })
  showMailInfo()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const showMailInfo = () => {
  setTimeout(() => {
    setTableSelect(true, true)
  }, 10)
}

const handleIsSelectFirstMailChange = (isSelectFirstMail) => {
  setTableSelect(isSelectFirstMail, filterParams.value.isOnlyMainContact)
}

const handleIsOnlyMailContactChange = (isOnlyMailContact) => {
  setTableSelect(filterParams.value.isSelectFirstMail, isOnlyMailContact)
}

const handleIsShowResignContactChange = (isShowResignContact) => {
  if (!isShowResignContact) {
    queryData.value.forEach((data) => {
      if (data.contact.workState == resignOptionId.value) {
        tableRef.value.getTableRef().toggleRowSelection(data, false)
      }
    })
  }
}

const rowStyle = ({ row }) => {
  if (row?.contact.workState == resignOptionId.value && !filterParams.value.isShowResignContact) {
    return { display: 'none' }
  } else return {}
}

const setTableSelect = (isSelectFirstMail, isOnlyMainContact) => {
  let lastContactId = 0
  tableRef.value.getTableRef().data.forEach((row) => {
    if (!filterParams.value.isShowResignContact && row.contact.workState == resignOptionId.value)
      return
    if (
      ((isSelectFirstMail && lastContactId != row.contact.id) || !isSelectFirstMail) &&
      ((isOnlyMainContact && row.contact.isMain) || !isOnlyMainContact)
    )
      tableRef.value.getTableRef().toggleRowSelection(row, true)
    else tableRef.value.getTableRef().toggleRowSelection(row, false)
    lastContactId = row.contact.id
  })
  selectCount.value = tableRef.value.getTableRef().getSelectionRows().length
}

const handleTableSelectChange = (newSelection) => {
  filterParams.value.isOnlyMainContact = false
  filterParams.value.isSelectFirstMail = false
  let count = 0
  newSelection.forEach((row) => {
    if (!filterParams.value.isShowResignContact && row.contact.workState == resignOptionId.value)
      return
    count++
  })
  selectCount.value = count
}

const resetForm = () => {
  filterParams.value = {
    isIndeterminate: false,
    isSelectFirstMail: true,
    isOnlyMainContact: true,
    isShowResignContact: false
  }
}

const emit = defineEmits(['success'])
/** 提交表单 */
const handleClickNextStep = () => {
  let mailAddresses = [] as any[]
  tableRef.value
    .getTableRef()
    .getSelectionRows()
    .forEach((row) => {
      if (!filterParams.value.isShowResignContact && row.contact.workState == resignOptionId.value)
        return
      mailAddresses.push({ id: row.contact.id, mailAddress: row.mailAddress })
    })
  if (selectCount.value == 0) {
    message.error('请选择邮件地址')
    return
  }
  dialogVisible.value = false
  marketEditRef.value.open({ mailAddresses: mailAddresses, type: 'create', id: 0 })
}

const mailMarketSuccess = () => {
  dialogVisible.value = false
  emit('success')
}
</script>
